package com.by.service.impl;

import com.by.common.utils.RedisUtils;
import com.by.mapper.GoodsMapper;
import com.by.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class GoodsServiceImpl implements GoodsService {

    private final String SK_LIST = "sklist";//秒杀缓存
    private final int SK_LIST_TTL = 2000;//秒


    @Autowired
    RedisUtils redisUtils;

    @Autowired
    GoodsMapper goodsMapper;

    @Override
    public List<Map> query() {
        List<Map> list = null;
        //查询缓存
//        Object obj = redisUtils.get(SK_LIST);
        Object obj = redisUtils.getForEntity(SK_LIST);
        if (null == obj) {
            //缓存没 查询数据库
            list = goodsMapper.query();
            redisUtils.setEx(SK_LIST, list, SK_LIST_TTL);
            //缓存商品 数量
            //遍历集合
            if(null!=list){
                Iterator<Map> it=list.iterator();
                while(it.hasNext()){
                    Map tmpMap=it.next();
                    String key="goods:id:"+tmpMap.get("id");
                    redisUtils.set(key,tmpMap.get("stock").toString());
                    redisUtils.set(key + ":price", tmpMap.get("price").toString());
                    redisUtils.set(key + ":goodsname", tmpMap.get("goodsname").toString());
                }
            }
        } else {
            list = (List<Map>) obj;
        }
        return list;
    }
}